<template> 
    <!-- 添加和搜索 -->
    <div class="search_add"> 
        <div width="176px">
            <el-button type="primary" size="large" @click="addUserbut">添加</el-button> 
            <el-button type="danger" size="large" @click="revomveUsers" :disabled="selectedIds.selectedIdsValue.length===0">批量删除</el-button>  
        </div> 
        <el-form inline width="400px">
            <el-form-item  style="width: 220px;">
                <el-input v-model="searchObj.username" placeholder="用户名"  size="large"></el-input>
            </el-form-item>
            <el-button type="primary" size="large" @click="queryuser">查询</el-button>
            <el-button size="large" @click="emptysearch">清空</el-button> 
        </el-form>
    </div>
    <!-- 列表 -->
    <el-table  
    :data="loginStore.UserListData.items" 
    border stripe 
    :header-cell-style="{background:'#eee'}" 
    :highlight-current-row="true" 
    :resizable="false" 
    @selection-change="handleSelectionChange"
    >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="150" align="center"/>
        <el-table-column prop="nickName" label="用户昵称" align="center"/>
        <el-table-column prop="roleName" label="权限列表" align="center"/> 
        <el-table-column prop="gmtCreate" label="创建时间" width="180" align="center"/>
        <el-table-column prop="gmtModified" label="更新时间" width="180" align="center"/> 
        <el-table-column label="操作" align="center">
            <template #default="scope" >
                <el-button type="success" size="small" @click="Jurisdiction(scope.row)">角色</el-button>
                <el-button type="primary" size="small" @click="alterBnt(scope.row)">修改</el-button>
                <el-button type="danger" size="small" @click="deleteUser(scope.row)">删除</el-button> 
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        :current-page="pagination.page"
        :total="loginStore.UserListData.total"
        :page-size="pagination.limit"
        :page-sizes="[1,5, 10, 20, 50, 100]"
        style="padding: 20px 0;"
        layout="prev, pager, next, jumper, ->, sizes, total"
        @current-change="getUserlist"
        @size-change="handleSizeChange"
        
    /> 
    <!-- 添加 -->
    <el-dialog v-model="addUser.dialogFormVisible" title="添加用户">
        <el-form :model="userForm" :rules="rules" ref="formRef">
            <el-form-item label="用户名" label-width="150px" prop="username">
                <el-input v-model="userForm.username" />
            </el-form-item>
            <el-form-item label="用户昵称" label-width="150px"> 
                <el-input v-model="userForm.nickName"  />
            </el-form-item>
            <el-form-item label="用户密码" label-width="150px" prop="password"> 
                <el-input v-model="userForm.password"  />
            </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="resetForm(formRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef)">
            确定
            </el-button>
        </span>
        </template>
    </el-dialog>
    <!-- 角色权限 -->
    <el-dialog v-model="control.dialogFormVisible" title="设置角色">
        <el-form label-width="80px">
            <el-form-item label="用户名">
                <el-input disabled :value="control.username"></el-input>
            </el-form-item>
            <el-form-item label="角色列表"> 
                <el-checkbox v-model="control.checkAll" :indeterminate="control.isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="control.userRoleIds" @change="handleCheckedChange">
                    <el-checkbox v-for="role in control.allRoles" :key="role.id" :label="role.id">
                        {{role.roleName}}
                    </el-checkbox>
                </el-checkbox-group> 
            </el-form-item>
            <div slot="footer">
                <el-button @click="control.dialogFormVisible=false">取消</el-button>
                <el-button type="primary" @click="saveRole">保存</el-button>
            </div>
        </el-form> 
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog v-model="alter.dialogFormVisible" title="修改用户名">
        <el-form label-width="80px" >
            <el-form-item label="用户名">
                <el-input v-model="alter.username" :value="alter.username"></el-input>
            </el-form-item>
            <el-form-item label="昵称">
                <el-input v-model="alter.nickName" :value="alter.nickName"></el-input>
            </el-form-item>
            <div slot="footer">
                <el-button @click="alter.dialogFormVisible=false">取消</el-button>
                <el-button type="primary" @click="saveAlter">保存</el-button>
            </div>
        </el-form>
    </el-dialog>
   <!--  <Finput v-model="value" clearable></Finput>
    {{ value }} -->
</template>

<script setup lang='ts'>
    // import Finput from './Finput.vue'
    import {ref,reactive   } from 'vue'  
    import { userAdd , deleteBatches , roleList ,roleUpdate ,userUpdate , delUser}  from '@/api'
    import type {userAlter} from '@/api'
    import {useloginStore} from '@/store/usePinia' 
    import type { FormRules,FormInstance } from 'element-plus'  
    import  { ElMessage ,ElMessageBox} from 'element-plus'   
    const value = ref('')
    // 仓库
    const loginStore = useloginStore();   
    // 分页
    const pagination = reactive({
        page: 1, // 当前页码
        limit: 10, // 每页数量
        total: 0, // 总数量  
    })
    // 搜索
    const searchObj = reactive({
        username:'',// 搜索
    })
    // 批量删除
    const selectedIds = reactive({
        selectedIdsValue:[]
    })
    // 权限
    const control = reactive({
        dialogFormVisible:false,
        userinfo:<any>[],
        username:'',    
        isIndeterminate:false,
        checkAll:false,
        userRoleIds:[],
        allRoles:[],
    }) 
    // 修改 
    const alter = reactive({
        dialogFormVisible:false,
        username:'',
        nickName:'', 
        userInfo:<userAlter>{},
    }) 
    // 添加表单 
    // const formSize = ref('default')
    const formRef = ref<FormInstance>() 
    const addUser = reactive({dialogFormVisible:false}) 
    const userForm = reactive({
        nickName:'',//昵称
        password:'',//密码  
        username:'',//账号
    }) 
    const rules = reactive<FormRules>({
        username:[
            { required: true, message: '用户名必须输入',trigger: ['blur', 'change'],},
            {  type: 'string',min: 5, max: 20, message: '用户名长度在 5 到 20 个字符之间', trigger: ['blur', 'change'],},
        ], 
        password:[
            { required: true,  message: '密码不能为空', trigger: 'blur'},
            { type: 'string', min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: ['blur', 'change'],},
        ],  
    })     
    // 用户列表
    function getUserlist(pagea?:number){ 
        pagination.page = pagea
        const { limit,page } = pagination;  
        loginStore.UserList(page, limit,{...searchObj}) 
    } 
    getUserlist(1)      
    // 分页条数监听
    function handleSizeChange (pageSize:number) {
        pagination.limit = pageSize 
        getUserlist(1)
    }
    // 添加用户
    async function submitForm(formEl: FormInstance | undefined){ 
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                // console.log('submit!')
                userAdd({...userForm}).then((res)=>{
                    if (res.code ==20000 ) {
                        console.log(res.data);
                        ElMessage.success("成功创建用户");
                        addUser.dialogFormVisible = false
                        // 更新数据
                        getUserlist(1)
                    }else{
                        ElMessage.error(res.message);
                    }
                })
            } else {
                ElMessage.error('请正确填写');
                return false
            }
        })
    }
    // 重置表单方法
    function resetForm(formEl: FormInstance | undefined) { 
        addUser.dialogFormVisible = false
        if (!formEl) return
        formEl.resetFields()
    } 
    // 关闭重置添加角色表单
    function addUserbut() {
        addUser.dialogFormVisible = true 
        if (formRef.value!=undefined) {
            formRef.value.resetFields()
        } 
    } 
    // 批量删除
    function handleSelectionChange(selection){
        selectedIds.selectedIdsValue = selection.map(item => item.id)
    }
    function revomveUsers(){ 
        ElMessageBox.confirm('此操作将删除该用户, 是否继续?').then(() => { 
            deleteBatches(selectedIds.selectedIdsValue).then((res) => {
                if(res.code == 20000){
                    getUserlist(1) //刷新数据
                    ElMessage.success('批量删成功')
                }else{
                    ElMessage.error('批量删失败')
                } 
            }) 
        }).catch(() => {
            ElMessage.info({ message: '已取消删除'});
        }); 
    }
    // 搜索
    function queryuser(){
        let username = searchObj.username.trim()
        if (username) {
            getUserlist(1)
        }
    }
    // 重置
    function emptysearch(){
        searchObj.username = ''
        getUserlist(1)
    }
    // 权限-获取当前角色权限
    function Jurisdiction(row){
        control.userinfo = row
        control.username = row.username
        control.dialogFormVisible = true
        roleList(row.id).then((res)=>{
            if (res.code == 20000) {
                let { allRolesList , assignRoles } = res.data
                control.allRoles = allRolesList
                control.userRoleIds = assignRoles.map(item => item.id)
                control.checkAll = allRolesList.length == assignRoles.length
                control.isIndeterminate = control.userRoleIds.length>0 && control.userRoleIds.length<allRolesList.length
            }
        }).catch(err=>{
            console.log(err); 
        })
    }
    function handleCheckAllChange(value){ 
        control.userRoleIds = value ? control.allRoles.map(item => item.id) : []
        control.isIndeterminate = false
    }
    function handleCheckedChange(){
        let {userRoleIds, allRoles } = control
        control.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
        control.isIndeterminate = userRoleIds.length >0 && userRoleIds.length < allRoles.length
    }
    // 更新角色权限
    function saveRole(){
        // userId,roleId
        const { userRoleIds,userinfo  } = control
        let userId = userinfo.id
        roleUpdate({userRoleIds,userId}).then((res) => {
            if (res.code ==20000) {
                ElMessage.success('角色设置成功!')
                control.dialogFormVisible = false
                getUserlist(1)     //更新数据 
            } else{
                ElMessage.error(res.message)
            } 
        }).catch((err) => {
            console.log(err); 
        });
    }
    // 更改用户名
    function alterBnt(row){
        alter.userInfo = row
        alter.username = row.username
        alter.nickName = row.nickName
        alter.dialogFormVisible = true 
    }
    function saveAlter(){
        let {userInfo,username,nickName} = alter
        userInfo.username =  username
        userInfo.nickName =  nickName 
        if (username != '') {
            userUpdate(userInfo).then((res) => {
                ElMessage.success('用户修改成功!')
                alter.dialogFormVisible = false 
            }).catch((err) => {
                ElMessage.error(err)
            });
        }else{
            ElMessage.error('用户名不能为空!')
        }
        
    }
    // 删除当前用户
    function deleteUser(row){
        ElMessageBox.confirm('此操作将删除该用户, 是否继续?').then(() => { 
            delUser(row.id).then((res) => {
                if(res.code == 20000){
                    getUserlist(1) //刷新数据
                    ElMessage.success('用户删成功')
                }else{
                    ElMessage.error('用户删失败')
                } 
            }) 
        }).catch(() => {
            ElMessage.info({ message: '已取消删除'});
        }); 
    }

</script>

<style lang='less' scoped>
    .search_add{
        width: 100%;
        height: 50px;
        display: flex;
        margin: 20px auto;
        justify-content:space-between;
        padding: 0 20px; 
        .el-form-item{
            margin-bottom: 0;
        } 
    }
    ::v-deep .el-table__inner-wrapper table thead tr th.el-table__cell{
        border-color:#dedfe0;
    }
</style>